<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <input type="file" id="upload">
  <!-- 原生图片压缩监听 -->
  <script>
    const accept = ['image/jpg', 'image/png', 'image/jpeg'];
    const maxSize = 1024 * 1024;
    const maxSize_str = '1MB';
    // 压缩成base64
    function convertImageToBase64 (file, callback) {
      let render = new FileReader;
      render.addEventListener('load', function(e) {
        const base64Image = e.target.result;
        callback && callback(base64Image);
        render = null;
      })
      render.readAsDataURL(file);
    }

    // base64压缩
    function compress(base64Image, callback) {
      // console.log(base64Image);
      let maxW = 500;
      let maxH = 300;
      const image = new Image();
      image.addEventListener('load', function(e){
        let ratio; // 图片的压缩比
        let needCompress = false; // 是否需要压缩
        console.log(image.naturalHeight,image.naturalWidth);

        // 经过处理后，实际图片尺寸
        if (maxW < image.naturalWidth) {
          needCompress = true;
          ratio = image.naturalWidth / maxW;
          maxH = image.naturalHeight / ratio;
        }
        
        // 经过处理后，实际图片尺寸
        if (maxH < image.naturalHeight) {
          needCompress = true;
          ratio = image.naturalHeight / maxH;
          maxW = image.naturalWidth / ratio;
        }
        
        // 如果不需要压缩，获取图片实际尺寸
        if (!needCompress) {
          maxW = image.naturalWidth;
          maxH = image.naturalHeight;
        }

        const canvas = document.createElement('canvas');
        canvas.setAttribute('id', '__compress__');
        canvas.width = maxW;
        canvas.height = maxH;
        canvas.style.visibility = 'hidden';
        document.body.appendChild(canvas);

        const ctx = canvas.getContext('2d');
        ctx.clearRect(0, 0, maxW, maxH);
        ctx.drawImage(image, 0, 0, maxW, maxH);
        
        const compressImage = canvas.toDataURL('image/png', 1);

        callback && callback(compressImage);

        const _image = new Image();
        _image.src = compressImage;
        document.body.appendChild(_image);

        canvas.remove();
      })
      image.src = base64Image;
      document.body.appendChild(image);
    }

    function uploadToServer (compressImage) {
      console.log('图片上传...')
    }

    const upload = document.getElementById('upload');
    upload.addEventListener('change',function(e){
      const [file] = e.target.files;
      console.log(file);
      if (!file) return;

      const { type: fileType, size: fileSize} = file;
      if (!accept.includes(fileType)) {
        upload.value = '';
        return alert(`不支持${fileType}文件类型!`);
      }

      if (fileSize > maxSize) {
        upload.value = '';
        return alert(`文件超出${maxSize_str}!`);
      }

      // 图片压缩
      convertImageToBase64(file, (base64Image) => compress(base64Image, uploadToServer));
    })
  </script>
</body>
</html>